package cn.sunxyz.common.site.controller;

import cn.sunxyz.common.site.Result;
import cn.sunxyz.common.site.domain.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.function.Supplier;

/**
 * Created by sunxyz on 2017/3/2.
 */
public abstract class DefaultController<D extends JpaRepository<T, PK>, T extends BaseEntity, PK extends Serializable> {

    @Autowired
    protected D repository;

    @Transactional
    public Result<String> add(T t) {
        try {
            Date now = new Date();
            t.setCreateTime(now);
            t.setUpdateTime(now);
            repository.save(t);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.ok();
    }

    @Transactional
    public Result<String> delete(PK id) {
        try {
            repository.delete(id);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.ok();
    }

    @Transactional
    public Result<String> update(T t) {
        try {
            Date now = new Date();
            t.setUpdateTime(now);
            repository.save(t);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error();
        }
        return Result.ok();
    }

    public <V> V $(Supplier<V> old, Supplier<V> news) {
        return news.get() == null ? old.get() : news.get();
    }

}
